/* 
 * @ProjectName VideoGoJar
 * @Copyright HangZhou Hikvision System Technology Co.,Ltd. All Right Reserved
 * 
 * @FileName CameraListActivity.java
 * @Description 这里对文件进行描述
 * 
 * @author xia xingsuo
 * @data 2015-11-5
 * 
 * @note 这里写本文件的详细功能描述和注释
 * @note 历史记录
 * 
 * @warning 这里写本文件的相关警告
 */
package com.videogo.ui.cameralist;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.videogo.constant.Constant;
import com.videogo.constant.IntentConsts;
import com.videogo.devicemgt.EZDeviceSettingActivity;
import com.videogo.exception.BaseException;
import com.videogo.exception.ErrorCode;
import com.videogo.open.R;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.openapi.bean.EZCameraInfo;
import com.videogo.remoteplayback.list.PlayBackListActivity;
import com.videogo.remoteplayback.list.RemoteListContant;
import com.videogo.scan.main.CaptureActivity;
import com.videogo.ui.discovery.SquareColumnActivity;
import com.videogo.ui.message.EZMessageActivity2;
import com.videogo.ui.realplay.EZRealPlayActivity;
import com.videogo.util.ConnectionDetector;
import com.videogo.util.DateTimeUtil;
import com.videogo.util.LogUtil;
import com.videogo.util.Utils;
import com.videogo.widget.PullToRefreshFooter;
import com.videogo.widget.PullToRefreshFooter.Style;
import com.videogo.widget.PullToRefreshHeader;
import com.videogo.widget.TitleBar;
import com.videogo.widget.WaitDialog;
import com.videogo.widget.pulltorefresh.IPullToRefresh.Mode;
import com.videogo.widget.pulltorefresh.IPullToRefresh.OnRefreshListener;
import com.videogo.widget.pulltorefresh.LoadingLayout;
import com.videogo.widget.pulltorefresh.PullToRefreshBase;
import com.videogo.widget.pulltorefresh.PullToRefreshBase.LoadingLayoutCreator;
import com.videogo.widget.pulltorefresh.PullToRefreshBase.Orientation;
import com.videogo.widget.pulltorefresh.PullToRefreshListView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static android.widget.ImageView.*;

/**
 * 摄像头列表
 */
public class EZCameraGridActivity extends Activity implements OnClickListener {
    private String TAG = "EZCameraGridActivity";
    private TitleBar mTitleBar = null;
    private List<EZCameraInfo> mCameraInfoList = new ArrayList<>();
    private BroadcastReceiver mReceiver = null;
    private EZOpenSDK mEZOpenSDK = null;

    private GridView gridView = null;

    private EZCameraGridAdapter mAdapter = null;

    @Override
    public void onClick(View view) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_page);
        initData();
        initView();
        Utils.clearAllNotification(this);
    }

    private void initView() {
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTitleBar.setTitle(R.string.cameras_txt);
        gridView = (GridView) findViewById(R.id.gridview);
        mAdapter = new EZCameraGridAdapter(this, mCameraInfoList);
        gridView.setAdapter(mAdapter);
        mTitleBar.addRightButton(R.drawable.my_add,
                new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(EZCameraGridActivity.this, CaptureActivity.class);
                        startActivity(intent);
                    }
                });
        ImageView iv = new ImageView(this);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(5, 5);
        iv.setLayoutParams(lp);
        iv.setImageDrawable(getResources().getDrawable(R.drawable.shuaxin));
        iv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                popLogoutDialog();
            }
        });
        mTitleBar.addLeftView(iv);
        ImageView iv2 = new ImageView(this);
        iv2.setLayoutParams(lp);
        iv2.setScaleType(ScaleType.CENTER_INSIDE);
        iv2.setImageDrawable(getResources().getDrawable(R.drawable.message_back_selector));
        iv2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mTitleBar.addLeftView(iv2);
    }

    private void initData() {
        mEZOpenSDK = EZOpenSDK.getInstance();
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                LogUtil.debugLog(TAG, "onReceive:" + action);
                if (action.equals(Constant.ADD_DEVICE_SUCCESS_ACTION)) {
//                    refreshButtonClicked();
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ADD_DEVICE_SUCCESS_ACTION);
        registerReceiver(mReceiver, filter);
        getCameraInfoList();
    }


///***********************刷新*************************//

    /**
     * 弹出登出对话框
     *
     * @see
     * @since V1.0
     */
    private void popLogoutDialog() {
        Builder exitDialog = new AlertDialog.Builder(EZCameraGridActivity.this);
        exitDialog.setTitle(R.string.exit);
        exitDialog.setMessage(R.string.exit_tip);
        exitDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                new LogoutTask().execute();
            }
        });
        exitDialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
        exitDialog.show();
    }


    private class LogoutTask extends AsyncTask<Void, Void, Void> {
        private Dialog mWaitDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mWaitDialog = new WaitDialog(EZCameraGridActivity.this, android.R.style.Theme_Translucent_NoTitleBar);
            mWaitDialog.setCancelable(false);
            mWaitDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            mEZOpenSDK.logout();
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            mWaitDialog.dismiss();
            mEZOpenSDK.openLoginPage();
            finish();
        }
    }


    ///*********************************获取用户的视屏列表*************************************//
    /**
     * 从服务器获取最新事件消息
     */
    private void getCameraInfoList() {
        if (this.isFinishing()) {
            return;
        }
        new GetCamersInfoListTask().execute();
    }
    /**
     * 获取事件消息任务
     */
    private class GetCamersInfoListTask extends AsyncTask<Void, Void, List<EZCameraInfo>> {
        private int mErrorCode = 0;


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected List<EZCameraInfo> doInBackground(Void... params) {
            if (EZCameraGridActivity.this.isFinishing()) {
                return null;
            }
            if (!ConnectionDetector.isNetworkAvailable(EZCameraGridActivity.this)) {
                mErrorCode = ErrorCode.ERROR_WEB_NET_EXCEPTION;
                return null;
            }

            try {
                List<EZCameraInfo> result = null;
                result = mEZOpenSDK.getCameraList(0, 100);
                return result;
            } catch (BaseException e) {
                mErrorCode = e.getErrorCode();
                return null;
            }
        }

        @Override
        protected void onPostExecute(List<EZCameraInfo> result) {
            super.onPostExecute(result);
            if (EZCameraGridActivity.this.isFinishing()) {
                return;
            }
            if (result != null) {
                Log.e(TAG, "result:" + result.size());
                mCameraInfoList.clear();
                mCameraInfoList.addAll(result);
                mAdapter.notifyDataSetChanged();
            }
            if (mErrorCode != 0) {
                onError(mErrorCode);
            }
        }

        protected void onError(int errorCode) {
            Log.e(TAG, "errorCode:" + errorCode);
        }
    }

}
